package day11;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * 需求：客户端通过键盘录入用户名，服务端对这个用户名进行校验。
 * 如果该用户存在，在服务端显示xxx，已登录。并在客户端显示xxx，欢迎光临。
 * 如果该用户存在，在服务端显示xxx，尝试登录。并在客户端显示xxx，该用户不存在。
 * 最多登录三次。
 *
 */
//客户端
public class UserLoginDemo {
    public static void main(String[] args)throws Exception  {
        Socket s=new Socket("127.0.0.1",8888);
        BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in ));
        PrintWriter out=new PrintWriter(s.getOutputStream(),true);
        BufferedReader bufin=new BufferedReader(new InputStreamReader(s.getInputStream()));
        for (int i = 0; i < 3; i++) {
            String line=bufr.readLine();
            out.println(line);
            String info=bufin.readLine();
            System.out.println("info:"+info);
        }
        bufr.close();
        s.close();
    }
}
//服务端
class LoginServer{
    public static void main(String[] args) throws Exception{
        ServerSocket ss=new ServerSocket(8888);
        while (true) {
            Socket s=ss.accept();
            new Thread(new UserThread(s)).start();
        }
    }
}
//多线程
class UserThread implements Runnable{
    private Socket s;
    public UserThread(Socket s) {
        super();
        this.s = s;
    }
    @Override
    public void run() {
// 服务端打印一下IP地址
        String ip = s.getInetAddress().getHostAddress();
        System.out.println(ip + "is connected");
        try {
            for (int i = 0; i <3; i++) {
                BufferedReader bufin=new BufferedReader(new InputStreamReader(s.getInputStream()));
                String name=bufin.readLine();//如果遇到ctrl键+c则会容易生成null
                if (name==null) {
                    break;
                }
                BufferedReader bufr=new BufferedReader(new FileReader("src\\main\\resources\\user.txt"));
                PrintWriter out=new PrintWriter(s.getOutputStream(),true);
                String line =null;
                boolean flag=false;
                while ((line=bufr.readLine())!=null) {
                    if (line.equals(name)) {
                        flag=true;
                        break;
                    }
                }
                if (flag) {
                    System.out.println(name+"，已登录");
                    out.println(name+"欢迎光临");
                    break;
                }else {
                    System.out.println(name+"，尝试登录");
                    out.println(name+"用户名不存在");
                    break;

                }
            }
            s.close();
        } catch (Exception e) {
            throw new RuntimeException(ip+"校验失败");
        }
    }

}
